package leetcode.lcp0018;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：76 ms, 在所有 Java 提交中击败了66.13%的用户
//
//内存消耗：55.9 MB, 在所有 Java 提交中击败了97.16%的用户
//
//通过测试用例：65 / 65
public class Solution implements IDebug {

	int mod = 1000000007;

	public int breakfastNumber(int[] staple, int[] drinks, int x) {
		int len1 = staple.length, len2 = drinks.length;
		int[] sortArr = null, forArr = null;
		if (len1 < len2) {
			sortArr = staple;
			forArr = drinks;
		} else {
			sortArr = drinks;
			forArr = staple;
		}
		Arrays.sort(sortArr);
		int R = sortArr.length - 1;
		long ans = 0;
		for (int element : forArr) {
			int rest = x - element;
			int l = 0, r = R;
			int find = -1;
			while (l <= r) {
				int mid = ((r - l) >> 1) + l;
				if (sortArr[mid] <= rest) {
					find = mid;
					l = mid + 1;
				} else {
					r = mid - 1;
				}
			}
			ans += find + 1;
			ans %= mod;
		}
		return (int) ans;
	}

	@Override
	public void debug4() {
		HelpDebug.compare(6, this.breakfastNumber(HelpDebug.str2array3("[10,20,5]"), HelpDebug.str2array3("[5,5,2]"), 15));
		HelpDebug.compare(8, this.breakfastNumber(HelpDebug.str2array3("[2,1,1]"), HelpDebug.str2array3("[8,9,5,1]"), 9));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
